package com.jswlw.common.wx;


import com.jswlw.common.utils.MD5Util;
import com.sun.xml.internal.ws.transport.Headers;

import java.security.MessageDigest;
import java.util.*;

public class SignUtil {

    private static String Key = "1494408192";

    private static String characterEncoding = "UTF-8";

    public static String MD5 = "MD5";

    private static String DATE_FORMAT = "";

    public static SortedMap map2SortedMap(Map<String, Object> map) {
        SortedMap sortedMap = new Headers();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            sortedMap.put(key, map.get(key));
        }
        return sortedMap;
    }

    public static Integer timeStamp() {
        String timestamp = String.valueOf(new Date().getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }

    /**
     * 验证签名
     *
     * @param token     微信服务器token，在env.properties文件中配置的和在开发者中心配置的必须一致
     * @param signature 微信服务器传过来sha1加密的证书签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return
     */
    public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
        String[] arr = new String[]{token, timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);

        // 将三个参数字符串拼接成一个字符串进行sha1加密
        String tmpStr = SHA1.encode(arr[0] + arr[1] + arr[2]);

        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    public static String createSign(String key, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign =  MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        System.out.println(origin);
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }
//
//    public static void main(String[] args) {
//        String s=MD5Encode("appid=wx29b24f43bca3ba85&body=自装（商用机）套餐&mch_id=1520252281&nonce_str=0082addbdfac443d8317cc8e14140cb5&notify_url=http://admin.xcs.iotwater.cn/api/wx/notifyPay&openid=orMZC1u42UCwGGPvweq4XGRkM4e4&out_trade_no=18122723350001&spbill_create_ip=202.98.122.129&total_fee=100&trade_type=JSAPI&key=13o7C7GpsTiw5snwVf0n92bkWzuwEbBF","UTF-8");
//        System.out.println(s);
//        s=MD5Encode("appid=wx29b24f43bca3ba85&body=自装（商用机）套餐&mch_id=1520252281&nonce_str=0082addbdfac443d8317cc8e14140cb5&notify_url=http://admin.xcs.iotwater.cn/api/wx/notifyPay&openid=orMZC1u42UCwGGPvweq4XGRkM4e4&out_trade_no=18122723350001&spbill_create_ip=202.98.122.129&total_fee=100&trade_type=JSAPI&key=13o7C7GpsTiw5snwVf0n92bkWzuwEbBF","UTF-8");
//        System.out.println(s);
//    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 参数进行XML化
     *
     * @param map,sign
     * @return
     */
    public static String parseString2Xml(Map<String, String> map, String sign) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = map.entrySet();
        Iterator iterator = es.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append("<" + k + ">" + v + "</" + k + ">");
        }
        sb.append("<sign>" + sign + "</sign>");
        sb.append("</xml>");
        System.out.println(sb.toString());
        return sb.toString();
    }
}
